package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.UserMapper;
import com.tedu.weibo.pojo.dto.UserLoginDTO;
import com.tedu.weibo.pojo.dto.UserRegDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.vo.UserVO;
import com.tedu.weibo.result.JsonResult;
import com.tedu.weibo.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
@Slf4j
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "用户注册")
    @PostMapping("/reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO){
        //System.out.println();
        log.trace("UserController.reg()方法被调用");
        log.debug("UserRegDTO"+userRegDTO);
        log.info("开始处理用户注册");
        System.out.println(userRegDTO);
        if(userMapper.selectByUsername(userRegDTO.getUsername()) != null){
            log.trace("用户名已存在");
            return new JsonResult(Status.USER_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        log.debug("User"+user);
        userMapper.insert(user);
        log.trace("UserController.reg()方法调用结束");
        return JsonResult.success();
    }
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if(user == null){
            return new JsonResult(Status.USERNAME_ERROR);
        }
        if(user.getPassword().equals(userLoginDTO.getPassword())){
            //将当前用户信息放入session中
            session.setAttribute("user",user);//相当于Map.put(K,V)
            return JsonResult.success();
        }
        return new JsonResult(Status.PASSWORD_ERROR);
    }
    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user != null){
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return JsonResult.success(userVO);
        }
        return new JsonResult(Status.NOT_LOGIN);
    }
    @ApiOperation(value = "用户注销")
    @GetMapping("/logout")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.success();
    }
}
